package com.shensi.adminCollect.controller.customer;

import com.shensi.adminCollect.common.constant.HttpStatus;
import com.shensi.adminCollect.common.constant.UserConstants;
import com.shensi.common.core.controller.BaseController;
import com.shensi.common.core.domain.AjaxResult;
import com.shensi.common.core.domain.ResultData;
import com.shensi.common.core.page.TableDataInfo;
import com.shensi.adminCollect.common.utils.MathUtil;
import com.shensi.adminCollect.common.utils.StringUtils;
import com.shensi.adminCollect.common.utils.poi.ExcelUtil;
import com.shensi.adminCollect.domain.customer.CustomerCardUseRecord;
import com.shensi.adminCollect.domain.customer.CustomerElectronicCard;
import com.shensi.adminCollect.domain.customer.ElecSumInfo;
import com.shensi.adminCollect.domain.customer.dto.CustomerCardChangeDto;
import com.shensi.adminCollect.domain.customer.from.UserBalanceForm;
import com.shensi.adminCollect.domain.customer.vo.UserBalanceSumVO;
import com.shensi.adminCollect.domain.customer.vo.UserBalanceVO;
import com.shensi.adminCollect.enums.customer.CardRecordType;
import com.shensi.adminCollect.service.customer.ICustomerElectronicCardService;
import com.shensi.adminCollect.vo.customer.CustomerElectronCardVo;
import com.shensi.adminCollect.vo.customer.ElectronicCardListVO;
import com.shensi.adminCollect.domain.system.SysAppUserInfoUser;
import com.shensi.adminCollect.domain.system.SysEnterpriseUser;
import com.shensi.adminCollect.domain.system.SysStationUser;
import com.shensi.adminCollect.service.system.IAppUserInfoUserService;
import com.shensi.adminCollect.service.system.ISysDeptService;
import com.shensi.adminCollect.service.system.ISysEnterpriseUserService;
import com.shensi.adminCollect.service.system.ISysStationUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.shensi.common.core.domain.model.LoginUser;
import com.shensi.common.core.utils.SecurityUtils;
import com.shensi.common.core.domain.entity.SysUser;
/**
 * 客户电子会员卡（储蓄卡）Controller
 *
 * @author qujia
 * @date 2021-04-12
 */
@RestController
@RequestMapping("/customer/card")
@Api(tags = "CustomerElectronicCardController", description = "电子卡相关controller")
public class CustomerElectronicCardController extends BaseController {

    private static final List<String> RECHARGE_PAY_TYPES = Collections.unmodifiableList(new ArrayList<String>() {{
        this.add(CardRecordType.WX_RECHARGE.getKey());
        this.add(CardRecordType.POS_RECHARGE.getKey());
        this.add(CardRecordType.MANUAL_ADD.getKey());
        this.add(CardRecordType.MANUAL_SUB.getKey());
        this.add(CardRecordType.REFUND.getKey());
    }});

    private static final List<String> PRESENT_PAY_TYPES = Collections.unmodifiableList(new ArrayList<String>() {{
        this.add(CardRecordType.WX_RECHARGE.getKey());
        this.add(CardRecordType.POS_RECHARGE.getKey());
        this.add(CardRecordType.MANUAL_ADD.getKey());
        this.add(CardRecordType.POS_PRESENT.getKey());
        this.add(CardRecordType.CONSUME_PRESENT.getKey());
        this.add(CardRecordType.CONSUME_PRESENT_CONSUME_REFUND.getKey());
        this.add(CardRecordType.REFUND.getKey());
    }});

    private static final List<String> CONSUME_PAY_TYPES = Collections.unmodifiableList(new ArrayList<String>() {{
        this.add(CardRecordType.DZK_CONSUME.getKey());
        this.add(CardRecordType.CONSUME_REFUND.getKey());
    }});

    @Autowired
    private ICustomerElectronicCardService customerElectronicCardService;
    @Resource
    private IAppUserInfoUserService appUserInfoUserService;
    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysStationUserService stationUserService;

    @Autowired
    private ISysEnterpriseUserService enterpriseUserService;


    /**
     * 查询客户电子会员卡（储蓄卡）列表
     */
    @GetMapping("/list")
    public TableDataInfo list(CustomerElectronicCard customerElectronicCard) {
        List<String> list = deptService.levelShareCardList(customerElectronicCard.getLevelId());
        if (list != null && list.size() > 0) {
            customerElectronicCard.setStationIdList(list);
            customerElectronicCard.setStationId(null);
        }
        startPage();
        List<CustomerElectronicCard> cardList = customerElectronicCardService.selectCustomerElectronicCardList(customerElectronicCard);
        return getDataTable(cardList);
    }

    /**
     * 导出客户电子会员卡（储蓄卡）列表
     */
    @GetMapping("/export")
    public AjaxResult export(CustomerElectronicCard customerElectronicCard) {
        List<CustomerElectronicCard> list = customerElectronicCardService.selectCustomerElectronicCardList(customerElectronicCard);
        ExcelUtil<CustomerElectronicCard> util = new ExcelUtil<CustomerElectronicCard>(CustomerElectronicCard.class);
        return util.exportExcel(list, "card");
    }

    /**
     * 获取客户电子会员卡（储蓄卡）详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(customerElectronicCardService.selectCustomerElectronicCardById(id));
    }

    /**
     * 新增客户电子会员卡（储蓄卡）
     */
    @PostMapping
    public AjaxResult add(@RequestBody CustomerElectronicCard customerElectronicCard) {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        customerElectronicCard.setStationId(currentUser.getUser().getEnterpriseId());
        customerElectronicCard.setStationName(currentUser.getUser().getEnterprise().getEnterpriseName());
        return toAjax(customerElectronicCardService.insertCustomerElectronicCard(customerElectronicCard));
    }

    /**
     * 修改客户电子会员卡（储蓄卡）
     */
    @PutMapping
    public AjaxResult edit(@RequestBody CustomerElectronicCard customerElectronicCard) {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        customerElectronicCard.setStationId(currentUser.getUser().getEnterpriseId());
        customerElectronicCard.setStationName(currentUser.getUser().getEnterprise().getEnterpriseName());
        return toAjax(customerElectronicCardService.updateCustomerElectronicCard(customerElectronicCard));
    }

    /**
     * 删除客户电子会员卡（储蓄卡）
     */
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(customerElectronicCardService.deleteCustomerElectronicCardByIds(ids));
    }

    /**
     * 查询电子会员数据
     */
    @GetMapping("/listSum")
    public AjaxResult listSum(CustomerElectronicCard customerElectronicCard) {
        LoginUser current = SecurityUtils.getLoginUser();
        SysStationUser sysStationUser = new SysStationUser();
        sysStationUser.setEnterpriseId(current.getUser().getEnterpriseId());
        List<SysStationUser> list = stationUserService.selectSysStationUserList(sysStationUser);
        List<String> list1 = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (SysStationUser s : list) {
                list1.add(s.getStationId() + "");
            }
            customerElectronicCard.setStationIdList(list1);
        }
        CustomerElectronicCard card = customerElectronicCardService.listSum(customerElectronicCard);
        return AjaxResult.success(card);
    }

    /**
     * 会员卡统计信息
     */
    @GetMapping("/cardUserSum")
    @ApiOperation(value = "余额明细统计接口", notes = "余额明细统计接口")
    public AjaxResult cardUserSum(CustomerCardUseRecord customerCardUseRecord, @RequestParam(required = false) String usageType) {
        LoginUser current = SecurityUtils.getLoginUser();

        String userName = current.getUser().getUserName();

        Long enterpriseId = "admin".equals(userName) ? customerCardUseRecord.getEnterpriseId() : current.getUser().getEnterpriseId();
        customerCardUseRecord.setEnterpriseId(enterpriseId);
        //油站账号
        if ("2".equals(current.getUser().getUserLevel())) {
            customerCardUseRecord.setStationId(current.getUser().getStationId().intValue());
        }


        //customer_electronic_card表里的stationId其实保存的是enterpriseId 0.0
//        List<CustomerElectronicCard> cardlist = customerElectronicCardService.cardUserSum(customerElectronicCard);
//        for(CustomerElectronicCard customerElectronicCard1:cardlist){
//            if("1".equals(customerElectronicCard1.getCardOilsType())){
//                customerElectronicCard.setQyAmt(customerElectronicCard1.getCumamt());
//            }
//            if("2".equals(customerElectronicCard1.getCardOilsType())){
//                customerElectronicCard.setCyAmt(customerElectronicCard1.getCumamt());
//            }
//            if("3".equals(customerElectronicCard1.getCardOilsType())){
//                customerElectronicCard.setLNGAmt(customerElectronicCard1.getCumamt());
//            }
//            if("4".equals(customerElectronicCard1.getCardOilsType())){
//                customerElectronicCard.setCNGAmt(customerElectronicCard1.getCumamt());
//            }
//        }

//        电子卡充值统计
        List<String> payTypeList = new ArrayList<>();
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(customerCardUseRecord.getPayType())) {
            payTypeList = Arrays.stream(customerCardUseRecord.getPayType().split(",")).collect(Collectors.toList());
        }
        customerCardUseRecord.setPayTypeList(payTypeList);
        CustomerCardUseRecord rechargeSumForm = new CustomerCardUseRecord();
        BeanUtils.copyProperties(customerCardUseRecord, rechargeSumForm);
        if (CollectionUtils.isEmpty(payTypeList)) {
            rechargeSumForm.setPayTypeList(RECHARGE_PAY_TYPES);
        } else {
            payTypeList.retainAll(RECHARGE_PAY_TYPES);
            rechargeSumForm.setPayTypeList(payTypeList);
        }
        List<ElecSumInfo> rechargeSum;
        if (CollectionUtils.isEmpty(rechargeSumForm.getPayTypeList())) {
            rechargeSum = Collections.emptyList();
        } else {
            rechargeSum = customerElectronicCardService.getRechargeSum(rechargeSumForm);
        }
        CustomerElectronCardVo customerElectronCardVo = new CustomerElectronCardVo();
        BigDecimal electronCardTotalRecharge = BigDecimal.ZERO;


        for (ElecSumInfo elecSumInfo : rechargeSum) {
            if (StringUtils.isNotEmpty(usageType) && "1".equals(usageType)) {
                break;
            }
            String type = elecSumInfo.getType();
            BigDecimal amt = Objects.isNull(elecSumInfo.getAmt()) ? BigDecimal.ZERO : elecSumInfo.getAmt();
            switch (type) {
                case "0":
                    customerElectronCardVo.setGenericElectronCardTotalRecharge(amt);
                    break;
                case "1":
                    customerElectronCardVo.setGasElectronCardTotalRecharge(amt);
                    break;
                case "2":
                    customerElectronCardVo.setDieselElectronCardTotalRecharge(amt);
                    break;
                case "3":
                    customerElectronCardVo.setLngElectronCardTotalRecharge(amt);
                    break;
                case "4":
                    customerElectronCardVo.setCngElectronCardTotalRecharge(amt);
                    break;

            }
            electronCardTotalRecharge = electronCardTotalRecharge.add(amt);
        }

        CustomerCardUseRecord presentSumForm = new CustomerCardUseRecord();
        BeanUtils.copyProperties(customerCardUseRecord, presentSumForm);
        // 电子卡赠送统计
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(customerCardUseRecord.getPayType())) {
            payTypeList = Arrays.stream(customerCardUseRecord.getPayType().split(",")).collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(payTypeList)) {
            presentSumForm.setPayTypeList(PRESENT_PAY_TYPES);
        } else {
            payTypeList.retainAll(PRESENT_PAY_TYPES);
            presentSumForm.setPayTypeList(payTypeList);
        }
        List<ElecSumInfo> presentSum;
        List<ElecSumInfo> manualDeductions = new ArrayList();
        if (CollectionUtils.isEmpty(presentSumForm.getPayTypeList())) {
            presentSum = Collections.emptyList();
        } else {
            presentSum = customerElectronicCardService.getRechargeSum(presentSumForm);
            manualDeductions = customerElectronicCardService.getManualDeduction(presentSumForm);
        }
        BigDecimal electronCardTotalPresentAmt = BigDecimal.ZERO;
        Map<String, BigDecimal> map = ElecSumInfo.listToMap(manualDeductions);
        for (ElecSumInfo elecSumInfo : presentSum) {
            if (StringUtils.isNotEmpty(usageType) && "1".equals(usageType)) {
                break;
            }
            String type = elecSumInfo.getType();
            BigDecimal presentAmt = Objects.isNull(elecSumInfo.getPresentAmt()) ? BigDecimal.ZERO : elecSumInfo.getPresentAmt();
            if (map != null && map.get(type) != null){
                presentAmt = presentAmt.subtract(map.get(type));
            }
            switch (type) {
                case "0":
                    customerElectronCardVo.setGenericElectronCardTotalPresentAmt(presentAmt);
                    break;
                case "1":
                    customerElectronCardVo.setGasElectronCardTotalPresentAmt(presentAmt);
                    break;
                case "2":
                    customerElectronCardVo.setDieselElectronCardTotalPresentAmt(presentAmt);
                    break;
                case "3":
                    customerElectronCardVo.setLngElectronCardTotalPresentAmt(presentAmt);
                    break;
                case "4":
                    customerElectronCardVo.setCngElectronCardTotalPresentAmt(presentAmt);
                    break;
            }
            electronCardTotalPresentAmt = electronCardTotalPresentAmt.add(presentAmt);
        }

        //电子卡消费统计
        CustomerCardUseRecord consumeSumForm = new CustomerCardUseRecord();
        BeanUtils.copyProperties(customerCardUseRecord, consumeSumForm);
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(customerCardUseRecord.getPayType())) {
            payTypeList = Arrays.stream(customerCardUseRecord.getPayType().split(",")).collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(payTypeList)) {
            consumeSumForm.setPayTypeList(CONSUME_PAY_TYPES);
        } else {
            payTypeList.retainAll(CONSUME_PAY_TYPES);
            consumeSumForm.setPayTypeList(payTypeList);
        }
        List<ElecSumInfo> consumeSum;
        if (CollectionUtils.isEmpty(consumeSumForm.getPayTypeList())) {
            consumeSum = Collections.emptyList();
        } else {
            consumeSum = customerElectronicCardService.getConsumeSum(consumeSumForm);
        }
        BigDecimal electronCardTotalConsume = BigDecimal.ZERO;

        for (ElecSumInfo elecSumInfo : consumeSum) {
            if (StringUtils.isNotEmpty(usageType) && "0".equals(usageType)) {
                break;
            }
            String type = elecSumInfo.getType();
            BigDecimal amt = MathUtil.add(elecSumInfo.getAmt(), elecSumInfo.getPresentAmt()).negate();
            switch (type) {
                case "0":
                    customerElectronCardVo.setGenericElectronCardTotalConsume(amt);
                    break;
                case "1":
                    customerElectronCardVo.setGaseElectronCardTotalConsume(amt);
                    break;
                case "2":
                    customerElectronCardVo.setDieselElectronCardTotalConsume(amt);
                    break;
                case "3":
                    customerElectronCardVo.setLngElectronCardTotalConsume(amt);
                    break;
                case "4":
                    customerElectronCardVo.setCNGElectronCardTotalConsume(amt);
                    break;
            }
            electronCardTotalConsume = electronCardTotalConsume.add(amt);
        }

        boolean cardUseForAll = false;
        if (enterpriseId != null) {
            SysEnterpriseUser enterprise = enterpriseUserService.selectSysEnterpriseUserById(enterpriseId);
            if (enterprise != null) {
                cardUseForAll = StringUtils.equals("1", enterprise.getCardUseRangeFlag());
            }
        }
        //电子卡余额统计
        CustomerElectronicCard card = new CustomerElectronicCard();
        card.setMobilePhone(customerCardUseRecord.getMobilePhone());
        card.setCardOilsType(customerCardUseRecord.getCardOilsType());
        card.setEnterpriseId(customerCardUseRecord.getEnterpriseId());
        List<ElecSumInfo> balanceSum = customerElectronicCardService.getBalanceSum(card, cardUseForAll);
        BigDecimal electronCardTotalBalance = BigDecimal.ZERO;
        for (ElecSumInfo elecSumInfo : balanceSum) {
            String type = elecSumInfo.getType();
            BigDecimal amt = Objects.isNull(elecSumInfo.getAmt()) ? BigDecimal.ZERO : elecSumInfo.getAmt();

            switch (type) {
                case "0":
                    customerElectronCardVo.setGenericElectronCardTotalBalance(amt);
                    break;
                case "1":
                    customerElectronCardVo.setGasElectronCardTotalBalance(amt);
                    break;
                case "2":
                    customerElectronCardVo.setDieselElectronCardTotalBalance(amt);
                    break;
                case "3":
                    customerElectronCardVo.setLngElectronCardTotalBalance(amt);
                    break;
                case "4":
                    customerElectronCardVo.setCngElectronCardTotalBalance(amt);
                    break;
            }
            electronCardTotalBalance = electronCardTotalBalance.add(amt != null ? amt : BigDecimal.ZERO);

        }


        customerElectronCardVo.setElectronCardTotalConsume(electronCardTotalConsume);
        customerElectronCardVo.setElectronCardTotalRecharge(electronCardTotalRecharge);
        customerElectronCardVo.setElectronCardTotalBalance(electronCardTotalBalance);
        customerElectronCardVo.setElectronCardTotalPresentAmt(electronCardTotalPresentAmt);

        return AjaxResult.success(customerElectronCardVo);
    }

    @GetMapping("/selectCard")
    public TableDataInfo selectCard(CustomerElectronicCard customerElectronicCard) {
        List<String> list = deptService.levelShareCardList(customerElectronicCard.getLevelId());
        List<CustomerElectronicCard> querylist = new ArrayList<>();
        List<CustomerElectronicCard> pagelist = new ArrayList<>();
        if (list != null && list.size() > 0) {
            customerElectronicCard.setStationIdList(list);
            customerElectronicCard.setStationId(null);
            customerElectronicCard.setStrSql(StringUtils.join(list, ","));
            querylist = customerElectronicCardService.selectCard(customerElectronicCard);
            pagelist = customerElectronicCardService.selectCardPage(customerElectronicCard);
        }
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(querylist);
        rspData.setTotal(pagelist.size());
        return rspData;
    }

    /**
     * 查询电子会员数据
     */
    @GetMapping("/listHYData")
    public AjaxResult listHYData(CustomerElectronicCard customerElectronicCard) {
//        List<String> list = deptService.levelDeptList(customerElectronicCard.getLevelId());
//        if(list!=null && list.size()>0){
//            customerElectronicCard.setStationIdList(list);
//            customerElectronicCard.setStationId(null);
//        }
        LoginUser current = SecurityUtils.getLoginUser();
        SysStationUser sysStationUser = new SysStationUser();
        sysStationUser.setEnterpriseId(current.getUser().getEnterpriseId());
        List<SysStationUser> list = stationUserService.selectSysStationUserList(sysStationUser);
        List<String> list1 = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (SysStationUser s : list) {
                list1.add(s.getStationId() + "");
            }
            customerElectronicCard.setStationIdList(list1);
        }
        return AjaxResult.success(customerElectronicCardService.listHYData(customerElectronicCard));
    }


    /**
     * 查询电子会员数据
     */
    @GetMapping("/listJRHYData")
    public AjaxResult listJRHYData(CustomerElectronicCard customerElectronicCard) {
//        List<String> list = deptService.levelDeptList(customerElectronicCard.getLevelId());
//        if(list!=null && list.size()>0){
//            customerElectronicCard.setStationIdList(list);
//            customerElectronicCard.setStationId(null);
//        }
        LoginUser current = SecurityUtils.getLoginUser();
        SysStationUser sysStationUser = new SysStationUser();
        sysStationUser.setEnterpriseId(current.getUser().getEnterpriseId());
        List<SysStationUser> list = stationUserService.selectSysStationUserList(sysStationUser);
        List<String> list1 = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (SysStationUser s : list) {
                list1.add(s.getStationId() + "");
            }
            customerElectronicCard.setStationIdList(list1);
        }

        return AjaxResult.success(customerElectronicCardService.listJRHYData(customerElectronicCard));
    }

    @GetMapping("user/list")
    @ApiOperation(value = "查询会员电子卡列表", response = ElectronicCardListVO.class)
    public AjaxResult customerCardList(@RequestParam String mobilePhone,
                                       @RequestParam Long enterpriseId) {
        ElectronicCardListVO vo = customerElectronicCardService.queryCustomerCardList(mobilePhone, enterpriseId);
        return AjaxResult.success(vo);
    }

    @PostMapping("/user/updateUserRecord")
    @ApiOperation(value = "更新会员电子卡余额")
    public AjaxResult updateUserReocrd(@RequestBody @Validated CustomerCardChangeDto customerCardChangeDto) {
        return customerElectronicCardService.updateUserReocrd(customerCardChangeDto);
    }

    @GetMapping("/user/balance/list")
    @ApiOperation(value = "电子卡账户列表", response = UserBalanceVO.class)
    public TableDataInfo userBalanceVOList(UserBalanceForm form) {
        initParam(form);
        if (form.getMemberCode() != null && !form.getMemberCode().equals("")) {
            SysAppUserInfoUser userFormForMemberCode = new SysAppUserInfoUser();
            userFormForMemberCode.setMemberCode(form.getMemberCode());
            SysAppUserInfoUser userForMemberCode = appUserInfoUserService.getOne(userFormForMemberCode);
            if (userForMemberCode != null) {
                form.setMobilePhone(userForMemberCode.getMobilePhone());
                int intValue = userForMemberCode.getStationId().intValue();
                form.setEnterpriseId(intValue);
            } else {
                form.setMobilePhone("9999999999");
            }
        }
        startPage();
        List<UserBalanceVO> userBalanceVOS = customerElectronicCardService.queryUserBalanceVOList(form);
        return getDataTable(userBalanceVOS);
    }

    @GetMapping("/user/balance/sum")
    @ApiOperation("电子卡账户总计")
    public ResultData<UserBalanceSumVO> userBalanceSum(UserBalanceForm form) {
        initParam(form);
        return ResultData.success(customerElectronicCardService.sumUserBalanceVO(form));
    }

    private void initParam(UserBalanceForm form) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        if (StringUtils.equals(UserConstants.LEVEL_TWO, sysUser.getUserLevel())) {
            // 油企
            form.setEnterpriseId(Math.toIntExact(sysUser.getEnterpriseId()));
        } else if (StringUtils.equals(UserConstants.LEVEL_THREE, sysUser.getUserLevel())) {
            // 油站
            form.setEnterpriseId(Math.toIntExact(sysUser.getEnterpriseId()));
            form.setStationId(Math.toIntExact(sysUser.getStationId()));
        }

        Integer enterpriseId = form.getEnterpriseId();
        if (enterpriseId != null) {
            SysEnterpriseUser enterpriseUser = enterpriseUserService.selectSysEnterpriseUserById(Long.valueOf(enterpriseId));
            if (enterpriseUser != null) {
                form.setCardUserForAll(StringUtils.equals("1", enterpriseUser.getCardUseRangeFlag()));
            }
        }

    }


}
